﻿using System;
using System.Drawing;
using System.IO;
using System.Net;
using System.Text;

namespace CTTest.Common
{
    sealed class HttpUtil
    {
        public static string GetRawHtml(string url, CookieContainer cc = null, string data = null, string method = "POST", Encoding encode = null, bool writeCookie = false)
        {
            if (encode == null)
                encode = Encoding.UTF8;


            if (method == "GET")
            {
                if (data != null)
                    url += "?" + data;
            }

            HttpWebRequest wr = (HttpWebRequest)WebRequest.Create(url);

            wr.Accept = "*/*";

            if (cc != null)
            {
                wr.CookieContainer = cc;
            }
            else if (writeCookie)
                throw new ArgumentException("cc is null while writeCookie is true");

            if (method == "POST")
            {
                if (data != null)
                {
                    byte[] dataArray = encode.GetBytes(data);
                    wr.Method = method;
                    wr.ContentType = "application/x-www-form-urlencoded";
                    wr.ContentLength = dataArray.Length;

                    using (Stream r = wr.GetRequestStream())
                    {
                        r.Write(dataArray, 0, dataArray.Length);
                    }
                }
            }

            HttpWebResponse response = (HttpWebResponse)wr.GetResponse();
            if (writeCookie)
            {
                cc.Add(response.Cookies);
            }

            Stream s = response.GetResponseStream();
            using (StreamReader sr = new StreamReader(s, encode))
            {
                return sr.ReadToEnd();
            }
        }

        public static Image GetImage(string url, CookieContainer cc = null)
        {
            HttpWebRequest wr = (HttpWebRequest)WebRequest.Create(url);

            wr.Accept = "*/*";

            if (cc != null)
            {
                wr.CookieContainer = cc;
            }

            Stream s = wr.GetResponse().GetResponseStream();
            return Image.FromStream(s);
        }
    }
}
